import React, { useState } from 'react';
import PropTypes from 'prop-types';
import FinishedSvg from './images/finished.svg';
import ProcessingSvg from './images/processing.svg';
import { WAITING_TASK_STATES, PROCESSING_TASK_STATES } from '@util/constants';
import { Progress, Button, Popconfirm, message, Popover } from 'antd';
import _ from 'lodash';
import { cancelTask, stopTask, resumeTask } from '@api/task';
import TaskExportModal from '../task-export-modal';
import './index.less';

const statusTextMap = {
  readying: '准备中',
  waiting: '未开始',
  end: '已完成',
  running: '运行中',
  paused: '已暂停'
};

const Status = props => {
  const { task = {} } = props;
  const percent = _.get(task, 'progress.progress', 0);
  const { status, isDeleted = false, runAt = {}, scanType } = task;
  const { isRunAt = false, hasRun = true, time } = runAt;
  let statusImg = null;
  let statusText = null;
  let statusProcess = null;
  let operateButton = null;

  const [exportModalType, setExportModalType] = useState(false);

  const onStopTask = () => {
    const _id = task._id;
    cancelTask(_id)
      .then(() => {
        message.success('成功下发终止任务请求');
      })
      .catch(() => {
        message.error('下发终止任务请求失败');
      });
  };

  const onPausedTask = () => {
    const _id = task._id;
    stopTask(_id)
      .then(() => {
        message.success('成功下发暂停任务请求');
      })
      .catch(() => {
        message.error('下发暂停任务请求失败');
      });
  };

  const onStartTask = () => {
    const _id = task._id;
    resumeTask(_id)
      .then(() => {
        message.success('成功下发启动任务请求');
      })
      .catch(() => {
        message.error('下发启动任务请求失败');
      });
  };

  const getProgress = (strokeColor = '#1890FF') => {
    const { status } = task;
    if (status === 'stopping') {
      return '-';
    } else {
      const { scanType } = task;
      const engineProgress = _.get(task, 'progress.engineProgress', []);

      const kmap = _.find(engineProgress, { name: 'kmap' }) || {};
      const xmap = _.find(engineProgress, { name: 'xmap' }) || {};
      const wmap = _.find(engineProgress, { name: 'wmap' }) || {};
      const pocsuite3 = _.find(engineProgress, { name: 'pocsuite3' }) || {};
      const nuclei = _.find(engineProgress, { name: 'nuclei' }) || {};
      const nscan = _.find(engineProgress, { name: 'nscan' }) || {};
      let popoverDesc = [];
      if (scanType !== 'OneDay') {
        popoverDesc.push({ ...kmap, name: '存活探测引擎' }, { ...xmap, name: '资产探测引擎' });

        if (
          _.get(
            task,
            `${
              scanType === 'Zoomeye' ? 'maxDetectionTaskParams' : 'onedayTaskParams'
            }.webFingerprintDetection`,
            false
          )
        ) {
          popoverDesc.push({ ...wmap, name: 'Web探测引擎' });
        }
      }
      if (scanType !== 'Zoomeye') {
        let nucleiDist = {};
        let pocsuite3Dist = {};
        let nscanDist = {};
        [nuclei, pocsuite3, nscan].forEach(r => {
          if (r) {
            let dist;
            if (r.name === 'pocsuite3') {
              dist = pocsuite3Dist;
            } else if (r.name === 'nscan') {
              dist = nscanDist;
            } else {
              dist = nucleiDist;
            }
            Object.keys(r).forEach(i => {
              dist[`${i}_${r.name}`] = r[i];
            });
          }
        });
        popoverDesc.push({ ...pocsuite3Dist, name: '漏洞检测引擎', ...nucleiDist, ...nscanDist });
      }
      //  仅端口存活只有kmap
      if (
        _.get(task, 'maxDetectionTaskParams.portDetectionOnly', false) ||
        _.get(task, 'onedayTaskParams.portDetectionOnly', false)
      ) {
        popoverDesc = [{ ...kmap, name: '存活探测引擎' }];
      }

      const progress = _.get(task, 'progress.progress', 0);
      const successFuc = desc => {
        let sum = _.get(desc, 'success', 0) + _.get(desc, 'failure', 0);
        if (desc.success_nuclei) {
          sum += desc.success_nuclei + _.get(desc, 'failure_nuclei', 0);
        }
        if (desc.success_nscan) {
          sum += desc.success_nscan + _.get(desc, 'failure_nscan', 0);
        }
        if (desc.success_pocsuite3) {
          sum += desc.success_pocsuite3 + _.get(desc, 'failure_pocsuite3', 0);
        }
        return sum;
      };
      const totalFuc = desc => {
        let sum = _.get(desc, 'total', 0) + _.get(desc, 'failure', 0);
        if (desc.total_nuclei) {
          sum += desc.total_nuclei + _.get(desc, 'failure_nuclei', 0);
        }
        if (desc.total_nscan) {
          sum += desc.total_nscan + _.get(desc, 'failure_nscan', 0);
        }
        if (desc.total_pocsuite3) {
          sum += desc.total_pocsuite3 + _.get(desc, 'failure_pocsuite3', 0);
        }
        return sum;
      };
      return (
        <Popover
          content={popoverDesc.map(desc => {
            return (
              <div key={desc.name}>
                {desc.name}
                {successFuc(desc)}/{totalFuc(desc)}:
                {statusTextMap[desc.status] ? statusTextMap[desc.status] : '未开始'}
              </div>
            );
          })}
        >
          <div className="process">
            <Progress
              style={{ maxWidth: '250px' }}
              percent={progress}
              strokeColor={strokeColor}
              showInfo={false}
            />
          </div>
        </Popover>
      );
    }
  };

  if (WAITING_TASK_STATES.indexOf(status) !== -1 && !isDeleted) {
    statusImg = <img src={ProcessingSvg} />;
    statusText = '等待中';
    operateButton = null;

    if (isRunAt && !hasRun) {
      statusText = (
        <>
          等待中
          <br />
          <span
            style={{
              color: 'rgba(0, 0, 0, 0.65)',
              fontSize: 14
            }}
          >
            预计 {time} 开始准备执行
          </span>
        </>
      );
    } else {
      statusText = '等待中';
    }
    if (status === 'paused') {
      statusText = `已暂停  ${_.get(task, 'progress.progress', 0)}%`;
      statusProcess = getProgress('#F8954A');
      operateButton = (
        <Popconfirm title="确定启动启动吗?" onConfirm={onStartTask}>
          <Button type="primary" size="small">
            启动
          </Button>
        </Popconfirm>
      );
    }
  } else if (PROCESSING_TASK_STATES.indexOf(status) !== -1 && !isDeleted) {
    statusImg = <img src={ProcessingSvg} />;

    if (scanType === 'OneDay') {
      statusText = `执行中 ${percent}％`;
      statusProcess = (
        <div className="progress">
          <Progress percent={percent} showInfo={false} />
        </div>
      );
    } else {
      statusText = `执行中  ${_.get(task, 'progress.progress', 0)}%`;
      statusProcess = getProgress();
    }

    operateButton = (
      <div className="btn-box">
        <Popconfirm title="确定暂停任务吗?" onConfirm={onPausedTask}>
          <Button type="primary" size="small">
            暂停
          </Button>
        </Popconfirm>
        <Popconfirm title="确定终止任务吗?" onConfirm={onStopTask}>
          <Button className="btn-stop" type="primary" size="small">
            终止
          </Button>
        </Popconfirm>
      </div>
    );
  } else {
    statusImg = <img src={FinishedSvg} />;
    statusText = !isDeleted ? '已完成' : '该任务已被逻辑删除';

    operateButton = (
      <Button type="primary" className="export" onClick={() => setExportModalType(true)}>
        导出报告
      </Button>
    );
  }

  return (
    <div className="tmd-c-status">
      <div className="img">{statusImg}</div>
      <div className="text" style={{ ...(isDeleted ? { fontSize: 12 } : {}) }}>
        {statusText}
      </div>
      {statusProcess}
      <div className="btn">{operateButton}</div>
      <TaskExportModal
        isDetail={true}
        task={task || {}}
        visible={exportModalType}
        onVisibleChange={setExportModalType}
      />
    </div>
  );
};

Status.propTypes = {
  task: PropTypes.object,
  percent: PropTypes.number,
  alive: PropTypes.number,
  enableProcess: PropTypes.bool
};

export default Status;
